﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Collections.Generic;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Linq;


namespace Common
{
    public class CommonAPI
    {
        public static Result GetResut(string szResult)
        {
            Result result = new Result();
            try
            {
                System.Xml.Linq.XElement doc = System.Xml.Linq.XElement.Parse(szResult);
                result.result = (doc.Element("result").Value == "True") ? true : false;
                result.command = doc.Element("command").Value;
                result.error = doc.Element("error").Value;
                result.data = doc.Element("data").Value;

                //byte[] buff = System.Convert.FromBase64String(doc.Element("data").Value);
                //System.Text.UTF8Encoding ut8Encoding = new System.Text.UTF8Encoding();
                //result.data = ut8Encoding.GetString(buff, 0, buff.Length);
            }
            catch (Exception e)
            {
                result.result = false;
                result.error = e.Message;
            }
            return result;
        }


        //public static Result GetResut(string szResult)
        //{
        //    Result result = new Result();
        //    try
        //    {
        //        using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(new System.IO.StringReader(szResult)))
        //        {
        //            if (xmlReader.ReadToFollowing("result"))
        //            {
        //                string temp = xmlReader.ReadInnerXml();
        //                result.result = (temp == "TRUE") ? true : false;
        //            }

        //            if (xmlReader.ReadToFollowing("command"))
        //                result.command = xmlReader.ReadInnerXml();

        //            if (xmlReader.ReadToFollowing("data"))
        //                result.data = xmlReader.ReadInnerXml();

        //            if (xmlReader.ReadToFollowing("error"))
        //                result.error = xmlReader.ReadInnerXml();
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        result.result = false;
        //        result.error = e.Message;
        //    }
        //    return result;
        //}

        public static void InvokeWebAPI(Delegate webClient_DownloadStringCompleted, string func_type, string op_tag, object[] objs)
        {
            string szParams = "";
            if (objs != null)
            {
                for (int i = 0; i < objs.Length; i++)
                {
                    szParams += (((objs[i].ToString() == "") ? "NULL" : objs[i].ToString()) + ",");
                }

                if (szParams.Length > 0)
                {
                    szParams = szParams.Remove(szParams.Length - 1, 1);
                }
            }



            string szURI = string.Format("http://takip.is-by.us:8280/WebAPI.aspx?func_type={0}&op_type={1}&params={2}", func_type, op_tag, szParams);
            //string szURI = string.Format("http://jpyoun.iptime.org:8280/WebAPI.aspx?func_type={0}&op_type={1}&params={2}", func_type, op_tag, szParams);
            //string szURI = string.Format("http://jhlee74.iptime.org:8280/WebAPI.aspx?func_type={0}&op_type={1}&params={2}", func_type, op_tag, szParams);
            //string szURI = string.Format("http://localhost:8280/WebAPI.aspx?func_type={0}&op_type={1}&params={2}", func_type, op_tag, szParams);

            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += (System.Net.DownloadStringCompletedEventHandler)webClient_DownloadStringCompleted;
            webClient.DownloadStringAsync(new Uri(szURI));
        }

        public static void InvokeWebAPIByPost(Delegate uploadStringCompleted, string func_type, string op_tag, object[] objs)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("func_type");
            sb.Append("=");
            sb.Append(func_type);
            sb.Append("&");
            sb.Append("op_tag");
            sb.Append("=");
            sb.Append(op_tag);
            sb.Append("&");
            sb.Append("params");
            sb.Append("=");
            //sb.Append(string.Format("{0}", (objs == null)? 0 :objs.Length));
            string szParams = "";
            if (objs != null)
            {
                for (int i = 0; i < objs.Length; i++)
                {
                    szParams += (((objs[i].ToString() == "") ? "NULL" : objs[i].ToString()) + ",");
                }

                if (szParams.Length > 0)
                {
                    szParams = szParams.Remove(szParams.Length - 1, 1);
                    sb.Append(szParams);
                }
            }

            //if (objs != null)
            //{
            //    for (int i = 0; i < objs.Length; i++)
            //    {
            //        sb.Append("&");
            //        sb.Append(string.Format("param_{0}", i));
            //        sb.Append("=");
                    
            //        string encoded = System.Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes((string)objs[i]));
            //        byte[] buff = System.Convert.FromBase64String(encoded);
            //        string decoded = System.Text.UTF8Encoding.Unicode.GetString(buff, 0, buff.Length);
            //        sb.Append((string)objs[i]);
            //    }
            //}

            string szURI = string.Format("http://takip.is-by.us:8280/WebAPI.aspx");
            //string szURI = string.Format("http://jpyoun.iptime.org:8280/WebAPI.aspx");
            //string szURI = string.Format("http://jhlee74.iptime.org:8280/WebAPI.aspx");
            //string szURI = string.Format("http://localhost:8280/WebAPI.aspx");
            try
            {
                WebClient webClient = new WebClient();
                webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
                webClient.UploadStringCompleted += (System.Net.UploadStringCompletedEventHandler)uploadStringCompleted;
                webClient.UploadStringAsync(new Uri(szURI), "post", sb.ToString());
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.StackTrace);
            }
            
        }

        public static List<DataClass> GetDataSource(string sResult, DataClass dataClass)
        {
            char sep = (char)127;

            if (sResult == null || sResult == "") return null;

            Tokenizer token = new Tokenizer(sResult);
            int row = int.Parse(token.StrTok(sep));
            int col = int.Parse(token.StrTok(sep));

            for (int i = 0; i < col; i++)
            {
                string sCaption = token.StrTok(sep);
                if (sCaption.Length > 1)
                {
                    switch (sCaption.Substring(0, 2))
                    {
                        case "_Y":
                        case "_F":
                        case "_T":
                        case "_B":
                            {
                                sCaption = sCaption.Remove(0, 2);
                            }
                            break;
                    }
                }
            }

            List<DataClass> lists = new List<DataClass>();
            for (int i = 0; i < row; i++)
            {
                System.Reflection.ConstructorInfo construct = dataClass.GetType().GetConstructor(new Type[0]);
                object obj = construct.Invoke(new object[0]);
                System.Reflection.MethodInfo method = obj.GetType().GetMethod("SetData");
                if (method != null)
                {
                    method.Invoke(obj, new object[1] { token });
                    lists.Add((DataClass)obj);
                }
            }
            return lists;
        }


        public static System.Collections.ObjectModel.ObservableCollection<Row> GetDataSource(string sResult)
        {
            char sep = (char)127;
            Tokenizer token = new Tokenizer(sResult);

            int row_cnt = int.Parse(token.StrTok(sep));
            int col_cnt = int.Parse(token.StrTok(sep));

            List<string> cols = new List<string>();
            for (int i = 0; i < col_cnt; i++)
            {
                DataGridTextColumn column = new DataGridTextColumn();
                string sCaption = token.StrTok(sep);
                if (sCaption.Length > 1)
                {
                    switch (sCaption.Substring(0, 2))
                    {
                        case "_Y":
                        case "_F":
                        case "_T":
                        case "_B":
                            {
                                sCaption = sCaption.Remove(0, 2);
                            }
                            break;
                    }
                }
                cols.Add(sCaption);
            }

            sep = (char)128;
            var rows = new System.Collections.ObjectModel.ObservableCollection<Row>();
            for (int i = 0; i < row_cnt; i++)
            {
                Row row = new Row();

                for (int j = 0; j < cols.Count; j++)
                {
                    row[cols[j]] = token.StrTok(sep);
                }
                rows.Add(row);
            }
            return rows;
        }


/*  Linq 사용 예)
 * 
            IEnumerable<Row> q = from r in rows
                                 where r["PID"].ToString() == "ROOT"
                                 select r;

            
            foreach (var t in q)
            {
                Liquid.Node item = new Liquid.Node();
                item.Title = t["TITLE"].ToString();
                item.FontSize = 11;
                item.ID = t["ID"].ToString();
                //item.Icon = "images/icongauge.png";
                item.Tag = t;

                
            }

*/
        //public static void MakeTree(Liquid.Tree tree, string szData)
        //{
        //    ObservableCollection<Row> rows = GetDataSource(szData);

        //    foreach (Row row in rows)
        //    {
        //        if (row["PID"].ToString() =="ROOT")
        //        {
        //            Liquid.Node item = new Liquid.Node();
        //            item.Foreground = new SolidColorBrush(Colors.White);
        //            item.Title = row["TITLE"].ToString();
        //            item.FontSize = 11;
        //            item.ID = row["ID"].ToString();
        //            //item.Icon = "images/icongauge.png";
        //            item.Tag = row;

        //            MakeNodes(rows, item);
        //            tree.Nodes.Add(item);
        //        }
   
        //    }
        //}

/*
                string parentID = row["PID"] as string;
                if (parentID.CompareTo("ROOT") == 0)
                {
                    Liquid.Node item = new Liquid.Node();
                    item.Title = row["TITLE"] as string;
                    item.FontSize = 11;
                    item.ID = row["ID"] as string;
                    //item.Icon = "images/icongauge.png";
                    item.Tag = row;
                    tree.Nodes.Add(item);
                }
                else
                {

                    Liquid.Node parentItem = (Liquid.Node)tree.Get(parentID);
                    if (parentItem != null)
                    {
                        Liquid.Node item = new Liquid.Node();
                        item.Title = row["TITLE"] as string;
                        item.FontSize = 11;
                        item.ID = row["ID"] as string;
                        //item.Icon = "images/icongauge.png";
                        item.Tag = row;
                        parentItem.Nodes.Add(item);
                    }
                }
 
 */
        //public static void MakeNodes(ObservableCollection<Row> rows , Liquid.Node pNode)
        //{
        //    foreach (Row r in rows)
        //    {
        //        if (r["PID"].ToString() == pNode.ID)
        //        {
        //            Liquid.Node item = new Liquid.Node();
        //            item.Foreground = new SolidColorBrush(Colors.White);
        //            item.Title = r["TITLE"].ToString();
        //            item.FontSize = 11;
        //            item.ID = r["ID"].ToString();
        //            //item.Icon = "images/icongauge.png";
        //            item.Tag = r;

        //            MakeNodes(rows, item);
        //            pNode.Nodes.Add(item);
        //        }

        //    }
        //}

        public static void ShowProgress(DependencyObject obj)
        {
            UserControl topUI = (UserControl)CommonAPI.GetTopUIElement(obj);
            if (topUI != null)
            {
                System.Reflection.MethodInfo method = topUI.GetType().GetMethod("ShowProgerss");
                if (method != null)
                {
                    method.Invoke(topUI, new object[1] {Visibility.Visible});
                }

            }
              
        }

        public static void HideProgress(DependencyObject obj)
        {
            UserControl topUI = (UserControl)CommonAPI.GetTopUIElement(obj);
            if (topUI != null)
            {
                System.Reflection.MethodInfo method = topUI.GetType().GetMethod("ShowProgerss");
                if (method != null)
                {
                    method.Invoke(topUI, new object[1] { Visibility.Collapsed });
                }

            }

        }


        public static  DependencyObject GetTopUIElement(DependencyObject obj)
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);

            while (parent != null)
            {
                DependencyObject tempParent = VisualTreeHelper.GetParent(parent);

                if (tempParent == null)
                    break;

                parent = tempParent;
            }

            return parent;
        }

    }
}
